package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 吴
 * @version V1.0
 * @Description
 * @Package com.itheima.service.Impl
 * @date 2021/11/24 17:14
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    private static final Logger logger = LoggerFactory.getLogger(OrderSettingServiceImpl.class);

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 通过日期月份查询当月全部的预约信息
     * @param date  时间格式：2021-11-01
     * @return  返回List集合 集合里面Map 的 key 值为当月号数
     */
    @Override
    public List<Map<String, Object>> getOrderSettingsByMonth(Date date) {
        return orderSettingDao.getOrderSettingsByMonth(date);
    }

    /**
     * 批量保存每天的预约人数
     * @param orderSettings 预约信息
     */
    @Override
    public void batchSaveOrderSetting(List<OrderSetting> orderSettings) {
        List<OrderSetting> orderSettingListUpdate = new ArrayList<>();
        List<OrderSetting> orderSettingListAdd = new ArrayList<>();

        // 循环遍历全部的信息
        orderSettings.stream().forEach(orderSetting ->{
            // 根据日期查询数据库是否有当天时期
            int count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
            if (count > 0) {
                // 说明数据库中有这条数据
                logger.info(orderSetting.toString());
                // 有：修改
                orderSettingListUpdate.add(orderSetting);
            }else{
                logger.info(orderSetting.toString());
                // 没有就添加
                orderSettingListAdd.add(orderSetting);
            }
        });

        // 添加
        if(!orderSettingListAdd.isEmpty()){
            orderSettingDao.batchAdd(orderSettingListAdd);
        }

        // 修改
        if(!orderSettingListUpdate.isEmpty()){
            orderSettingDao.batchUpdate(orderSettingListUpdate);
        }
    }

    /**
     * 保存单条预约人数
     * @param orderSetting 预约信息
     */
    @Override
    public void saveOrderSetting(OrderSetting orderSetting) {
        // 根据日期查询数据库是否有当天时期
        int count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count > 0) {
            // 修改
             orderSettingDao.updateByOrderDate(orderSetting);
        }else{
            // 保存
            orderSettingDao.add(orderSetting);
        }
    }

    /**
     * 根据日期查询当前是否可以预约
     * @param date 日期
     * @return
     */
    @Override
    public OrderSetting findByOrderDate(Date date) {
        return orderSettingDao.selectByOrderDate(date);
    }


}
